package csu.web.mypetstore.service;

import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.domain.LineItem;
import csu.web.mypetstore.domain.Order;
import csu.web.mypetstore.domain.Sequence;
import csu.web.mypetstore.persistence.ItemDao;
import csu.web.mypetstore.persistence.OrderDao;
import csu.web.mypetstore.persistence.LineItemDao;
import csu.web.mypetstore.persistence.SequenceDao;
import csu.web.mypetstore.persistence.impl.ItemDaoImpl;
import csu.web.mypetstore.persistence.impl.LineItemDaoImpl;
import csu.web.mypetstore.persistence.impl.OrderDaoImpl;
import csu.web.mypetstore.persistence.impl.SequenceDaoImpl;

import javax.sound.midi.InvalidMidiDataException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


//import static org.eclipse.jdt.internal.compiler.codegen.ConstantPool.ValueOf;
public class OrderService {

    private ItemDao itemDao;

    private OrderDao orderDao;

    private SequenceDao sequenceDao;

    private LineItemDao lineItemDao;

    public OrderService(){
        itemDao = new ItemDaoImpl();
        orderDao = new OrderDaoImpl();
        lineItemDao = new LineItemDaoImpl();
        sequenceDao = new SequenceDaoImpl();
    }
    public void insertOrder(Order order) throws InvalidMidiDataException {
        //插入订单数据及订单内商品数据
        orderDao.insertOrder(order);
        Iterator<LineItem> it = order.getLineItems().iterator();
        while (it.hasNext()){
            LineItem lineItem = (LineItem) it.next();
            lineItemDao.insertLineItem(lineItem);
        }

        System.out.println("inserOrder!");
    }

    public Order getOrder(int orderId) {
        return orderDao.getOrder(orderId);
    }

    public List<LineItem> getLineItemsByOrderId(int orderId){
        List<LineItem> lineItems = lineItemDao.getLineItemsByOrderId(orderId);
        //给lineItem安排上item(会自动算总价 实现在setItem函数中
        for(LineItem lineItem:lineItems){
            lineItem.setItem(itemDao.getItem(lineItem.getItemId()));
        }
        return lineItems;
    }

    public List<Order> getOrdersByUsername(String userid) {
        List<Order> orders =orderDao.getOrdersByUserid(userid);
        //给order安排上lineItem
        for (Order order:orders){
            List<LineItem> lineItems = getLineItemsByOrderId(order.getOrderId());
            order.setLineItems(lineItems);
        }
        return orders;
    }

    //其实是获取下一个订单编号的
    public int getNextId(String name) throws InvalidMidiDataException {
//        System.out.println("getnextid函数没写好 不知道干啥的 ");

        //获取当前的sequence
        Sequence sequence = sequenceDao.getSequence(name);

        //拿到下一个订单编号
        int nextId = sequence.getNextId();
        //提交下下个订单编号 用于下一次获取(当前的逻辑只是+1）
        sequence.setNextId(sequence.getNextId()+1);
        sequenceDao.updateSequence(sequence);
        //返回下个订单编号
        return nextId;
    }
}
